import { useState } from "react";
import { useDispatch } from "react-redux";
import { checkLogin } from "./store/modules/counterStore"; 
import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import className from 'classnames'
// import '../antd/dist/antd.css'
import './App.css';
const App = () => {
  // 修正 useState 解构方式
  const [formData, setFormData] = useState({
    account: '',
    password: ''
  });
  const handleKeyDown = (e) => {
    if (e.key === "Enter") {
      setAttemptedLogin(true);
      e.preventDefault();
      dispatch(checkLogin(formData))
    }
  };
  const handleClick = ()=>{
    setAttemptedLogin(true);
    dispatch(checkLogin(formData))
  };
  const [attemptedLogin, setAttemptedLogin] = useState(""); //尝试登录判断
  const isLoggedIn = useSelector(state => state.users.isLoggedIn);
  const navigate = useNavigate();
  useEffect(() => {
    console.log(isLoggedIn)
  if (attemptedLogin) {
    if (isLoggedIn) {
      navigate('/layout');
    }else {
      alert('账号或密码错误！'); // 密码错误提示
      setAttemptedLogin(false)
    }
  }
  }, [isLoggedIn, navigate, attemptedLogin]);
  // 处理输入变化
  const handleInputChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };
  const dispatch = useDispatch()
  return (
    <div className="page-container"> {/* 外层容器，用于渐变背景 */}
    <div className="login-container">
      <h2 className="title">Login</h2>
      <div className="input-group">
        <div className="label">account:</div>
        <input className="input"
          type="text" 
          name="account"  // 添加 name 属性
          value={formData.account}
          onChange={handleInputChange}
          onKeyDown={handleKeyDown}
        /> 
      </div>
      <div className="input-group">
        <div className="label" >Password:</div>
        <input className="input"
          type="password"  // 修改为 password 类型
          name="password"  // 添加 name 属性
          value={formData.password}
          onChange={handleInputChange}
          onKeyDown={handleKeyDown}
        /> 
      </div>
      <div>
        <button onClick={handleClick}>Login</button>
      </div>
    </div>
    </div>
  )
}
export default App